package com.dongxingx.renchuang.tablet.utils

import android.os.Handler
import android.util.Log
import java.io.File
import java.io.FileOutputStream
import java.io.PrintWriter
import java.util.*

/**
 * 二维码模块处理
 */
object GPIOHelper {
    private const val LED_CTL_PATH = "/sys/class/zh_gpio_out/out"
    private const val TAG = "GPIOHelper"
    private val handler = Handler()

    //关灯
//    private val LED_OFF_VAL = arrayOf(
//        "2",  //红灯
//        "4",  //绿灯
//        "6",  //摄像头白灯
//        "8",  //摄像头红灯
//        "12" //工作指示灯
//    )
//    //开灯
//    private val LED_ON_VAL = arrayOf(
//        "1",  //红灯
//        "3",  //绿灯
//        "5",  //摄像头白灯
//        "7",  //摄像头红灯
//        "11" //工作指示灯
//    )
    private enum class LedCTL(val param: String) {
        RED_ON("1"), RED_OFF("2"),
        CAMERA_RED_ON("7"), CAMERA_RED_OFF("8"),
        LED_RED_ON("1"), LED_RED_OFF("2"),
        LED_GREEN_ON("3"), LED_GREEN_OFF("4"),
        LED_WHITE_ON("5"), LED_WHITE_OFF("6"),
        RELAY_ON("9"), RELAY_OFF("10")
    }

    private var readQRTimer: Timer? = null

    fun relayOn() {
        ctlLed(LedCTL.RELAY_ON.param)
    }

    fun relayOff() {
        ctlLed(LedCTL.RELAY_OFF.param)
    }

    //关闭补光灯
    fun lightingOff() {
        ctlLed(LedCTL.LED_RED_OFF.param)
        ctlLed(LedCTL.LED_GREEN_OFF.param)
        ctlLed(LedCTL.LED_WHITE_OFF.param)
    }

    //打开补光灯
    fun lightingOn() {
        ctlLed(LedCTL.LED_RED_ON.param)
        ctlLed(LedCTL.LED_GREEN_ON.param)
        ctlLed(LedCTL.LED_WHITE_ON.param)
    }

    fun openDoor() {
        ctlLed(LedCTL.RELAY_ON.param)
        handler.postDelayed({
            ctlLed(LedCTL.RELAY_OFF.param)
        }, 200)

    }

    private fun ctlLed(cmd: String) {
        val file = File(LED_CTL_PATH)
        if (!file.exists() || !file.canWrite()) {
            Log.e(TAG, "文件不存在 或者 不可写")
            return
        }
        try {
            val fout = FileOutputStream(file)
            val pWriter = PrintWriter(fout)
            pWriter.println(cmd)
            pWriter.flush()
            pWriter.close()
            fout.close()

        } catch (ex: Throwable) {
            ex.printStackTrace()
        }
    }
}